package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LoginException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public int deleteByPrimaryKey(Long id) {
        return employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void insert(Employee record, Long[] roleIds) {
        employeeMapper.insert(record);
        // 添加中间表数据
        if (roleIds != null && roleIds.length > 0){
            employeeMapper.saveRelation(record.getId(),roleIds);
        }
    }

    @Override
    @Transactional
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public Employee login(String username, String password) {
        Employee employee = employeeMapper.selectByUsername(username);
        if (employee == null){
            throw new LoginException("账号错误");
        }else if (!employee.getPassword().equals(password)){
            throw new LoginException("密码错误");
        }
        return employee;
    }

    @Override
    public boolean checkUsername(String username) {
        return employeeMapper.checkUsername(username) != null;
    }

    @Override
    @Transactional
    public void updateByPrimaryKey(Employee record, Long[] roleIds) {
        employeeMapper.updateByPrimaryKey(record);
        // 删除中间表数据
        employeeMapper.deleteRelation(record.getId());
        // 添加中间表数据
        if (roleIds != null && roleIds.length > 0){
            employeeMapper.saveRelation(record.getId(),roleIds);
        }

    }

    @Override
    @Transactional
    public PageInfo<Employee> query(EmployeeQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> departments = employeeMapper.selectForList(qo);
        return new PageInfo(departments);
    }




}
